package org.dromara.common.translation.config

import com.fasterxml.jackson.databind.ObjectMapper
import io.github.oshai.kotlinlogging.KotlinLogging
import jakarta.annotation.PostConstruct
import org.dromara.common.translation.annotation.TranslationType
import org.dromara.common.translation.core.TranslationInterface
import org.dromara.common.translation.core.handler.TranslationBeanSerializerModifier
import org.dromara.common.translation.core.handler.TranslationHandler
import org.springframework.boot.autoconfigure.AutoConfiguration

/**
 * 翻译模块配置类
 *
 * @author LikeYouDo
 * @date 2025/07/26
 */
@AutoConfiguration
class TranslationConfig(
    private val list: MutableList<TranslationInterface<*>>,
    private val objectMapper: ObjectMapper
) {
    companion object{
        private val log = KotlinLogging.logger {  }
    }
    @PostConstruct
    fun init() {
        val map: MutableMap<String, TranslationInterface<*>> = HashMap(list.size)
        for (trans in list) {
            if (trans.javaClass.isAnnotationPresent(TranslationType::class.java)) {
                val annotation = trans.javaClass.getAnnotation(TranslationType::class.java)
                map.put(annotation.type, trans)
            } else {
                log.warn { trans.javaClass.getName() + " 翻译实现类未标注 TranslationType 注解!" }
            }
        }
        TranslationHandler.TRANSLATION_MAPPER.putAll(map)
        // 设置 Bean 序列化修改器
        objectMapper.serializerFactory = objectMapper.serializerFactory
            .withSerializerModifier(TranslationBeanSerializerModifier())
    }
}
